package com.jiaquyun.jcyx.main.mine

import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.OrderGood
import com.jiaquyun.jcyx.entity.OrderList
import com.jiaquyun.jcyx.jetpack.mode.OrderViewModel
import com.jiaquyun.jcyx.main.cart.OrderDetailsActivity
import com.jiaquyun.jcyx.main.cart.OrderPayActivity
import com.module.lemlin.LoadingDialog
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadCenterImage

import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_mine_order.*


class MineOrderFragment : OwnerViewModeFragment<OrderViewModel>() {

    companion object {
        const val KEY_COLLECT_ACTION = "KEY_COLLECT_ACTION"
        fun newInstance(action: Int): MineOrderFragment {
            val bundle = Bundle().apply {
                putInt(KEY_COLLECT_ACTION, action)
            }
            return MineOrderFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mOrderListAdapter =
        object : BaseQuickAdapter<OrderList, BaseViewHolder>(R.layout.item_order_group) {
            init {
                addChildClickViewIds(
                    R.id.rvOrderGroupCancel,
                    R.id.rvOrderGroupPayment,
                    R.id.rvOrderGroupConfirm
                )
            }

            override fun convert(holder: BaseViewHolder, item: OrderList) {
                holder.setText(
                    R.id.tvOrderGroupStatus,
                    if (item.order_status == "1" && item.pay_status == "0")
                        "待付款"
                    else if (item.order_status == "1" && item.pay_status == "1")
                        "待发货"
                    else if (item.order_status == "2" && item.pay_status == "1")
                        "待收货"
                    else if (item.order_status == "3" && item.pay_status == "1" && item.shipping_status != "0")
                        "已完成"
                    else "已取消"
                )
                    .setText(R.id.tvOrderGroupTime, item.createtime)
                    .setText(R.id.rvOrderGroupCount, "共${item.total_goods_num}件，实付")
                    .setText(R.id.rvOrderGroupPrice, "￥${item.order_amount}")
                holder.getView<RecyclerView>(R.id.rvOrderGroupGoods)
                    .adapter = OrderGoodsAdapter().apply {
                    setNewInstance(item.order_goods.take(2).toMutableList())
                    if (item.order_goods.size > 3) {
                        setFooterView(createFooterView())
                    }
                }

                holder.setGone(R.id.rvOrderGroupCancel, item.order_status != "1")

                holder.setGone(
                    R.id.rvOrderGroupPayment,
                    !(item.order_status == "1" && item.pay_status == "0")
                )

                holder.setGone(
                    R.id.rvOrderGroupConfirm,
                    !(item.order_status == "2" && item.pay_status == "1")
                )
            }

            inner class OrderGoodsAdapter :
                BaseQuickAdapter<OrderGood, BaseViewHolder>(R.layout.item_goods_order_list) {
                override fun convert(holder: BaseViewHolder, item: OrderGood) {
                    holder.setText(R.id.tvGoodsOrderListName, item.goods_name)
                        .setText(R.id.tvGoodsOrderListNum, "x${item.goods_num}")
                        .getView<ImageView>(R.id.ivGoodsOrderListIcon)
                        .loadCenterImage(item.image)
                }
            }

            private fun createFooterView(): View = TextView(context).apply {
                text = "..."
                textSize = 16f
                setTextColor(context.resources.getColor(R.color.FF_333333))
                setPadding(ConvertUtils.dp2px(63f), 0, 0, 0)
            }
        }

    private val mAction: String? by lazy {
        when (arguments?.getInt(KEY_COLLECT_ACTION) ?: 0) {
            0 -> ""
            1 -> "waitpay"
            2 -> "waitsend"
            3 -> "waitreceive"
            4 -> "finish"
            else -> null
        }
    }


    override fun viewModel(): OrderViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_mine_order

    private var isGoOrderDetails: Boolean = false

    override fun initView() {
        rvMineOrderBody.adapter = mOrderListAdapter

        mOrderListAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData = mOrderListAdapter.getItem(position)
            if (view.id == R.id.rvOrderGroupPayment) {
                isGoOrderDetails = false
                viewModel.orderDetail(itemData.id.toString())
            } else if (view.id == R.id.rvOrderGroupCancel) {
                viewModel.orderCancel(itemData.id.toString())
            } else if (view.id == R.id.rvOrderGroupConfirm) {
                viewModel.orderConfirm(itemData.id.toString())
            }
        }

        mOrderListAdapter.setOnItemClickListener { _, view, position ->
            val itemData = mOrderListAdapter.getItem(position)
            isGoOrderDetails = true
            viewModel.orderDetail(itemData.id.toString())
        }

        mSmartRefreshLayout.setEnableLoadMore(false)
        mSmartRefreshLayout.setOnRefreshListener {
            mAction?.let {
                viewModel.orderIndex(it)
            }
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            mAction?.let {
                viewModel.orderIndex(it, isLoadMore = true)
            }
        }
    }

    override fun initData() {
        mAction?.let {
            viewModel.orderIndex(it)
        }
    }

    override fun onRefreshLoad() {
        mAction?.let {
            viewModel.orderIndex(it)
        }
    }

    override fun initViewMode() {

        viewModel.orderListLiveDate.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg ?: "")
                mSmartRefreshLayout.finishLoadMore((false))
                mSmartRefreshLayout.finishRefresh()
            } else if (response.status == Status.SUCCESS) {
                mSmartRefreshLayout.finishLoadMore()
                mSmartRefreshLayout.finishRefresh()
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                if (it.data.size == 0) {
                    mOrderListAdapter.setEmptyView(createEmptyView())
                }
                if (it.loadMore) {
                    mOrderListAdapter.addData(it.data)
                } else {
                    mOrderListAdapter.setNewInstance(it.data)
                }
                if (it.data.size < viewModel.rows) {
                    mOrderListAdapter.setFooterView(createFooterView())
                    mSmartRefreshLayout.setEnableLoadMore(false)
                } else {
                    mOrderListAdapter.removeAllFooterView()
                    mSmartRefreshLayout.setEnableLoadMore(true)
                }
            }
        })

        viewModel.orderDetailsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(requireContext(), R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            } else {
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data ?: return@observe
            if (isGoOrderDetails) {
                OrderDetailsActivity.open(data)
            } else {
                OrderPayActivity.open(data)
            }
        })

        viewModel.orderCancelLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(requireContext(), R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            } else {
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            initData()
        })

        viewModel.orderConfirmLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(requireContext(), R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            } else {
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            initData()
        })
    }

    private fun createEmptyView(): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null)
    }

    private fun createFooterView(): View = TextView(requireContext()).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            ConvertUtils.dp2px(30f)
        )
        gravity = Gravity.CENTER
        textSize = 13f
        text = "没有更多数据"
        setTypeface(null, Typeface.BOLD)
        setTextColor(ColorUtils.getColor(R.color.FF_666666))
    }

}